<template>
  <div v-if="!printShow">
    <div class="front">
      <el-collapse v-model="activeNames" class="front-collapse"
        @change="activeNames = !activeNames; collapseName == '收起' ? collapseName = '展开' : collapseName = '收起'">
        <el-collapse-item :title="collapseName" class="collapse-1" name="1">
          <el-form :model="searchForm" label-width="120px">
            <el-form-item label="条码号" class="front-input">
              <el-input v-model="searchForm.barcode" />
            </el-form-item>
            <el-form-item label="调整单id" class="front-input">
              <el-input v-model="searchForm.checkOrderId" />
            </el-form-item>
            <!-- <el-form-item label="调整人员" class="front-input">
              <el-select v-model="searchForm.createById" placeholder="选择调整人员" @change="handleWarehouseChange">
                <el-option v-for="employee in employeeList" :key="employee.createById" :value="employee.createById" :label="employee.createBy"></el-option>
              </el-select>
            </el-form-item> -->
            <el-form-item label="选择时间" class="front-input">
              <div class="block">
                <el-date-picker
                  v-model="timeRange"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期时间"
                  end-placeholder="结束日期时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="选择日期时间范围"
                />
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="">查询</el-button>
              <el-button type="primary" @click="">重置</el-button>
            </el-form-item>
          </el-form>
        </el-collapse-item>
      </el-collapse>
    </div>

    <div class="tail">
      <div class="tail-action">
        <!-- 审核通过按钮 -->
        <el-button type="primary" @click="handleApprove">审核通过</el-button>
        <!-- 审核驳回按钮 -->
        <el-button type="danger" @click="handleReject">审核驳回</el-button>
        <el-button type="primary" @click="printSelectedRows">直接打印</el-button>
        <el-button type="primary" @click="designPrint">自定义打印</el-button>
        <el-popover placement="bottom" trigger="click">
          <template #reference>
            <el-button><el-icon>
                <List />
              </el-icon>显示设置</el-button>
          </template>
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <el-checkbox-group v-model="selectedFilters" @change="handleCheckChange">
            <el-checkbox v-for="item in tableFilter.map(i => i.label)" :label="item" :key="item" />
          </el-checkbox-group>
        </el-popover>
      </div>
      <el-table :data="tableData()" border style="width: 100%" :max-height="collapseName == '收起' ? 450 : 660" v-loading="tableLoading" @selection-change="handleChangeSelection">
        <template v-slot:empty>
          <div class="no-data">暂无数据</div>
        </template>
        <el-table-column type="selection" width="40" />
        <el-table-column v-for="item in inboundDataColumn" :prop="item.prop" :min-width="item.minWidth" :width="item.width"
          :max-width="item.maxWidth" :label="item.label">
          <!-- <template v-if="true" v-slot:default="scope">
            <div v-if="item.prop == 'orderType'">
              <el-tag v-if="scope.row[item.prop] == 0" type="success">采购入库</el-tag>
              <el-tag v-else-if="scope.row[item.prop] == 1" type="info">借货入库</el-tag>
            </div>
            <span v-else>{{ scope.row[item.prop] }}</span>
          </template> -->
        </el-table-column>
      </el-table>
      <div class="pagination" style="float: right; margin-top: 15px;">
        <el-pagination v-model:current-page="data.page" v-model:page-size="data.limit"
          layout="prev, pager, next ,total,sizes" v-model:total="data.total" @current-change="handleCurrentChange"
          @size-change="handleSizeChange" />
      </div>
    </div>
  </div>
  <div v-else>
    <a-button @click="printShow = false" type="primary" danger>退出打印页面</a-button>
    <print :provider="providerData" :printData="printDataProp"></print>
  </div>
</template>
    
<script>
import { defineComponent, reactive, toRefs, ref } from "vue";
import '@/mock/inbound.js'
import { onMounted, onBeforeMount } from "vue";
import { ElMessage } from "element-plus";
import { getAuditOrder, auditList, auditRequest } from '@/api/inbound/inbound'
import { getWarehouseListV2 } from '@/api/setting/setting';
import { getSupplierList } from "@/api/user/user"
import { List } from '@element-plus/icons-vue';
import { useRoute, useRouter } from "vue-router"
import { useStore } from 'vuex';
//打印页面
//打印界面
import print from '@/print/index.vue'
//打印标签组成
import { createElementTypes } from '@/api/inbound/auditPriceprint.js';
import provider from '@/api/inbound/auditPriceprint.js'
import { printData } from '@/api/inbound/auditPriceprint.js'

export default defineComponent({
  name: "HomeView",
  components: {
    List,
    print
  },
  setup() {
    //将打印标签界面传给print子组件
    const providerData = ref(provider)
    const printDataProp = ref(printData)
    const printShow = ref(false)

    const route = useRoute()
    const router = useRouter()
    const store = useStore()

    const remark = ref('123');// 备注
    const employeeList = ref([])// 调整人员
    const timeRange = ref([])// 时间选择器
    const rowDetails = ref({})
    const drawer = ref(false)
    const isIndeterminate = ref(false)
    const checkAll = ref(true)//显示设置是否全选
    const searchForm = reactive({  //入库查询表单数据
      barcode: null,
      checkOrderId: null,
      createById: null,
      startTime: null,
      endTime: null,
    })
    const { rules } = require('@/api/inbound/auditPriceprint.js');
    const inboundJadeData = ref([])
    const selectedFilters = ref([])
    const selectedRows = ref([])//已勾选记录
    const inboundDataColumn = ref([])//表头数据
    const supplierList = ref([])
    const warehouseList = ref([])
    const tableFilter = ref([
      { label: '审核状态', prop: 'status', width: '100', isdisabled: true, isSelected: true },
      { label: '调整人员', prop: 'auditedBy', width: '100', isdisabled: true, isSelected: true },
      { label: '创建时间', prop: 'createTime', width: '100', isdisabled: true, isSelected: true },
      { label: '调整时间 ', prop: 'auditTime', width: '100', isdisabled: true, isSelected: true },
      { label: '备注', prop: 'remark', width: '100', isdisabled: true, isSelected: true },
      { label: '调整单id', prop: 'id', width: '100', isdisabled: true, isSelected: true },
      { label: '条码', prop: 'barcode', width: '200', isdisabled: true, isSelected: true },
      { label: '成本', prop: 'costPrice', width: '100', isdisabled: true, isSelected: true },
      { label: '标价', prop: 'tagPrice', width: '200', isdisabled: true, isSelected: true },
      { label: '市场价', prop: 'marketPrice', width: '200', isdisabled: true, isSelected: true },
      { label: '货品名', prop: 'jadeName', width: '200', isdisabled: true, isSelected: true },
      { label: '原数量', prop: 'oriNum', width: '200', isdisabled: true, isSelected: true },
      { label: '调整后数量', prop: 'newNum', width: '200', isdisabled: true, isSelected: true },
    ])

    const collapseName = ref('展开');
    const activeNames = ref(false)

    //分页处理
    const state = reactive({//表格用到的参数
      data: {
        page: 1,
        limit: 10,
        total: inboundJadeData.value.length,
      }
    });

    // loading
    const tableLoading = ref(true)
    const tableData = () => {
      // console.log("inboundJadeData:",inboundJadeData)
      return inboundJadeData.value
    };
    const handleCurrentChange = (e) => {//改变页码
      state.data.page = e;
      handleGetInboundOrderList(e, state.data.limit)
    };
    const handleSizeChange = (e) => {//改变页数限制
      state.data.limit = e;
      handleGetInboundOrderList(state.data.page, e)
    };

    const handleGetInboundOrderList = () => {//获取入库单列表
      tableLoading.value = true
      const params = {
        type: 0
      }
      // console.log(params)
      auditList(params).then((res) => {
        console.log("auditList:",res)
        // 检查 res.rows 是否为 null，并根据情况进行赋值
        inboundJadeData.value = res.rows 
          ? res.rows.map(row => ({
              ...row,
              ...row.related
          })) 
          : [];
        console.log("inboundJadeData:",inboundJadeData);
        state.data.total = res.total
        tableLoading.value = false
      })
    }
    const handleCheckAllChange = (val) => {//全选按钮
      inboundDataColumn.value = []
      selectedFilters.value = []
      isIndeterminate.value = false;
      if (val) {
        tableFilter.value.forEach(item => {
          item.isSelected = val
          inboundDataColumn.value.push(item)
          selectedFilters.value.push(item.label)
        })
      }

    }
    const handleCheckChange = (val) => {//勾选列
      let temp = []
      tableFilter.value.forEach(item_t => {
        selectedFilters.value.forEach(item_s => {
          if (item_t.label == item_s) {
            temp.push(item_t)
          }
        })
      })
      if (temp.length < tableFilter.value.length && temp.length > 0) {
        isIndeterminate.value = true
      } else {
        isIndeterminate.value = false
      }
      inboundDataColumn.value = temp
      selectedFilters.value = inboundDataColumn.value.map(item => item.label)
    }

    onBeforeMount(() => {
      getSupplierList().then((res) => {
        supplierList.value = res.rows
      })
      getWarehouseListV2().then((res) => {
        warehouseList.value = res
      })
      handleGetInboundOrderList()
    })


    onMounted(() => {
      tableFilter.value.forEach(function (item, index) {
        if (item.isSelected) {
          selectedFilters.value.push(item.label)
          inboundDataColumn.value.push(item)
        }
      })
    })
    const mergeOrder = () => {

    }
    const onSearch = () => {
      const params = {
        pageSize: state.data.limit,
        pageNum: state.data.page,
        barcode: searchForm.barcode,
        checkOrderId: searchForm.checkOrderId,
        createById: searchForm.createById,
        startTime: timeRange.value[0]||null,
        endTime: timeRange.value[1]||null
      }
      console.log(params)
      auditList(params).then((res) => {
        console.log("auditList:",res)
        inboundJadeData.value = res.rows
        state.data.total = res.total
        tableLoading.value = false
      })
    }

    const audit = (status) => {
      const ids = selectedRows.value.map(row => row.id);
      const data = {
        status: status,
        ids: ids,
        remark: remark.value
      };

      auditRequest(data).then((res)=>{
        if (res.code === 200) {
          ElMessage.success('操作成功');
          handleGetInboundOrderList()
        } else {
          ElMessage.error('操作失败');
        }
      })
    };

    // 审核通过按钮的点击事件
    const handleApprove = () => {
      audit(1);
    };

    // 审核驳回按钮的点击事件
    const handleReject = () => {
      audit(2);
    };

    const handleChangeSelection = (selection) => {//已勾选的记录
      selectedRows.value = selection
      // console.log(selectedRows)
      // createElementTypes(selectedRows._rawValue)
      // console.log(printData)
    }
    const onReset=()=>{
      searchForm.checkOrderId=searchForm.barcode=searchForm.createById=searchForm.startTime=''
    }

    //直接打印价格调整单
    const printSelectedRows = () => {
      if (selectedRows.value.length == 0) {
        ElMessage.warning('请选择要打印的记录')
      } else {
        const printWindow = window.open('', '_blank');
        let content = `<html><head><title>打印</title>`

        content += `</head><body>`;
        content += `<h1>价格调整记录</h1>`
        content += `<table style="border-collapse: collapse; width: 100%;height: (0.42*width)">`;
        content += `<tr>
                  <th style="border: 1px solid black; padding: 8px;">审核状态</th>
                  <th style="border: 1px solid black; padding: 8px;">调整人员</th>
                  <th style="border: 1px solid black; padding: 8px;">创建时间</th>
                  <th style="border: 1px solid black; padding: 8px;">调整时间</th>
                  <th style="border: 1px solid black; padding: 8px;">备注</th>
                  <th style="border: 1px solid black; padding: 8px;">条码</th>
                  <th style="border: 1px solid black; padding: 8px;">成本</th>
                  <th style="border: 1px solid black; padding: 8px;">标价</th>
                  <th style="border: 1px solid black; padding: 8px;">市场价</th>
                  <th style="border: 1px solid black; padding: 8px;">货品名</th>
                  <th style="border: 1px solid black; padding: 8px;">原数量</th>
                  <th style="border: 1px solid black; padding: 8px;">调整后数量</th>
                  
                </tr>`;
        console.log(selectedRows.value)
        selectedRows.value.forEach(row => {
          content += `<tr>
                    <td style="border: 1px solid black; padding: 8px;">${row.status}</td>
                    <td style="border: 1px solid black; padding: 8px;">${row.auditedBy}</td>
                    <td style="border: 1px solid black; padding: 8px;">${row.createTime}</td>
                    <td style="border: 1px solid black; padding: 8px;">${row.auditTime}</td>
                    <td style="border: 1px solid black; padding: 8px;">${row.remark}</td>
                    <td style="border: 1px solid black; padding: 8px;">${row.barcode}</td>
                    <td style="border: 1px solid black; padding: 8px;">${row.costPrice}</td>
                     <td style="border: 1px solid black; padding: 8px;">${row.tagprice}</td>
                    <td style="border: 1px solid black; padding: 8px;">${row.marketPrice}</td>
                    <td style="border: 1px solid black; padding: 8px;">${row.jadeName}</td>
                    <td style="border: 1px solid black; padding: 8px;">${row.oriNum}</td>
                    <td style="border: 1px solid black; padding: 8px;">${row.newNum}</td>
                  </tr>`;
        });
        content += `</table></body></html>`;
        printWindow.document.open();
        printWindow.document.write(content);
        printWindow.document.close()
        printWindow.print()
        printWindow.onload = () => {

          printWindow.print();
          printWindow.close();
        };
        selectedRows.value = []
      }
    }
   //自定义打印价格调整单
   const designPrint = () => {
    // 需要一次数据更新
    const formData = {
        //...
    };
      // 将数据按照 auditPriceprint.js 的预期格式进行整理
      const formattedData = {};
       for (const key in formData) {
           if (rules[key]) {
               formattedData[`${key}1`] = formData[key];
           }
       }
       // 确保 formattedData 是一个数组或可迭代的对象
       createElementTypes(rules, [formattedData]);
       printDataProp.value = formattedData;
       printShow.value = true;
   };
    return {
      printShow,providerData,printDataProp,designPrint,// 打印的相关变量及方法
      inboundJadeData,
      searchForm, rowDetails, drawer,
      collapseName, warehouseList, supplierList,
      activeNames,timeRange,
      inboundDataColumn, selectedFilters, tableFilter, checkAll, isIndeterminate,
      tableData, mergeOrder, handleChangeSelection,printSelectedRows,createElementTypes,
      handleCurrentChange, handleSizeChange, handleCheckAllChange, handleCheckChange,
      handleGetInboundOrderList, onSearch,onReset,tableLoading,
      ...toRefs(state),
    };
  },
});


</script>
    #F8F8F8
    
<style rel="stylesheet/scss" lang="scss" scoped>
.front {
  background-color: #FFF;
  padding: 10px;

  .front-input {
    width: 320px;
  }
}

.center {
  margin-top: 10px;
  // border-top: 1px solid var(--el-border-color);
  // border-bottom: 1px solid var(--el-border-color);
}

.tail {
  background-color: #FFF;
  margin-top: 10px;
  padding: 10px;
}

.tail-action {
  display: flex;
  margin-bottom: 10px;
}


.center .center-data {
  height: 30px;
  width: 150px;
  border: 1px solid;
  border-radius: 10px;
  margin: 10px;
  text-align: center;
  font-size: 20px;
  background-color: #72f6ff;
}

.el-table {
  .el-button {
    margin-left: 0px; //调整按钮不对齐
  }
}

</style>
    